<template>
    <el-container>
        <!-- 顶部 -->
        <el-header>
            <!-- 顶部导航栏 -->
            <div>
                <div @click="routerPush('/index')">
                    <el-avatar shape="square" :size="large" :src="top.logoSrc" :key="top.logoSrc"></el-avatar>
                    <span>&nbsp;&nbsp;&nbsp;Comic漫漫</span>
                </div>
                <div>
                    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
                        <el-menu-item index="1">
                            <el-input placeholder="请输入内容" v-model="top.search" class="input-with-select">
                                <el-button slot="append" icon="el-icon-search" @click="routerPushSearch()"></el-button>
                            </el-input>
                        </el-menu-item>
                        <el-menu-item index="2" @click="getMainPageControllerQueryCoSpiderInfoListResource(keyword,userId)">源</el-menu-item>
                        <el-submenu index="3" @mouseover.native="getMainPageControllerQueryHistoryRecordPageResource()">
                            <template slot="title" >历史</template>
                            <el-menu-item index="2-1" v-for="item in (this.top.historyData == null ? [] : this.top.historyData.data)" :key="item" @click="routerPushDetail(item.jumpurl,item.spiderId)"><i class="el-icon-time"></i>{{item.title}}</el-menu-item>
                            <el-menu-item index="2-7" @click="routerPush('/manage/history')">&nbsp;&nbsp;&nbsp;查看全部</el-menu-item>
                        </el-submenu>
                        <el-submenu index="4" @mouseover.native="getMainPageControllerCoCollectInfoPageByUserResource()">
                            <template slot="title">收藏</template>
                            <el-menu-item index="2-1" v-for="item in (this.top.collectData == null ? [] : this.top.collectData.data)" :key="item" @click="routerPushDetail(item.jumpurl,item.spiderId)"><i class="el-icon-star-on"></i>{{item.title}}</el-menu-item>
                            <el-menu-item index="2-7" @click="routerPush('/manage/collect')">&nbsp;&nbsp;&nbsp;查看全部</el-menu-item>
                        </el-submenu>
                        <el-submenu index="5" @click.native="routerPush('/manage/profile')">
                            <template slot="title"><el-avatar :size="50" :src="uploadPicture(top.avatar)"></el-avatar></template>
                            <el-menu-item index="2-1"><i class="el-icon-user"></i> {{this.$store.state.common.username}}</el-menu-item>
                            <el-menu-item index="2-2"><i class="el-icon-message"></i> {{this.$store.state.common.email}}</el-menu-item>
                            <el-menu-item index="2-3" divided @click="logout()">退出登录</el-menu-item>
                        </el-submenu>
                    </el-menu>
                </div>
            </div>
        </el-header>
        <!-- 主体内容 -->
        <el-main>
            <div class="start-text"><span>“{{this.search.keyword}}”的搜索结果</span></div>
            <div class="my-search">
                <div class="my-search-card" v-for="item in this.search.data" :key="item" @click="routerPushDetail(item.jumpurl)"> 
                    <!--infinite-scroll-immediate="this.search.startLoading" :v-infinite-scroll="load()" :infinite-scroll-disabled="this.search.loading" -->
                    <div>
                        <el-image :src="agentPicture(item.picture,search.pyInfo.referer)" lazy>
                            <div slot="placeholder" class="image-slot">加载中<span class="dot">...</span></div>
                        </el-image>
                    </div>
                    <div>
                        <span>{{item.title}}</span>
                    </div>
                </div>
            </div>
            <div class="end-text">
                <span v-if="!search.loading">木有更多惹 ◐▽◑</span>
                <span v-if="search.loading">拼命加载中... </span>
            </div>
        </el-main>
        <!-- <el-footer>Footer</el-footer> -->
        <el-footer>
            <!-- 源 -->
            <el-drawer title="源" :visible.sync="top.drawer" direction="rtl">
                <div class="my-detail-recommend">
                    <div>
                        <!-- {{pyResultData}} -->
                        <!-- <span>推荐漫画</span>
                        <span><span>更多</span><i class="el-icon-arrow-right"></i> </span> -->
                    </div>
                    <div>
                        <div class="my-detail-recommend-card" v-for="item in pyResultData" :key="item" @click="closeDrawer(item)"> 
                            <div>
                                <el-image :src="uploadPicture(item.pictureUrl)">
                                    <div slot="placeholder" class="image-slot">加载中<span class="dot">...</span></div>
                                </el-image>
                            </div>
                            <div>
                                <span>名称: {{item.name}}</span>
                                <span>源: {{item.url}}</span>
                                <span>上传用户: {{item.userName}}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </el-drawer>
        </el-footer>
    </el-container>
</template>

<script>
import LogoSrc from '@/assets/icon/comic.png'
import Api from '@/api/index';

export default {
  name: 'Search',
  data () {
    return {
        /**
         * 导航头
         */
        //logo
        top: {
            logoSrc: LogoSrc,
            //数据来源 
            //抽屉打开状态 默认false;
            drawer: false,
            pySourceId: null,
            pyResultData: null,
            //历史记录
            pageIndex: 1,
            pageSize: 6,
            historyData: null,
            //收藏漫画
            collectData: null,
            //用户id,头像
            userId: this.$store.state.common.userId,
            avatar: this.$store.state.common.avatar, 
            //搜索 
            search: '',
        },
      /** 
       * 主体内容
       */
      search: {
          pyId: this.$route.query.id || this.$route.params.id,
          keyword: this.$route.query.keyword || this.$route.params.keyword,
          pageIndex: 1, //默认第一页
          loading: true, //加载状态 false:加载完毕, true :加载中
          startLoading: false, 
          total: 1, //总共页数默认1页
          data: null, // 漫画列表内容信息
          pyInfo: null //py文件信息
      },
      loading: {
          //监听是否已经到达底部
          flag : false,
          //延迟3秒再判断
          time : 3000,
          //监听是否已经到达了指定时间
          flag2 : true
      },
      msg: 'Welcome to Your Vue.js App',
      pictureUrl: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
    }
  },
  methods: {
            /**
       * 导航头
       */
      //点击跳转界面  
      routerPush(url){
        //   this.$router.push({path: url})
          let newWindow = this.$router.resolve({path: url})
          window.open(newWindow.href,'_blank')
      },
      /** 加载头像 */
      uploadPicture(url){
         return url == '' || url == undefined | url == null ? '' : Api.FILEROOT + url
      },
      //图片代理
      agentPicture(url,referer){
          let agentUrl = Api.APIROOT + '/agentController/forwardPicture?url=' + url + '&referer=' + referer
          return agentUrl
      },
      // python 数据源
      //修改抽屉打开状态
      drawerClick(){
          this.top.drawer = !this.top.drawer;
      },
      //修改源并关闭抽屉
      closeDrawer(item){
        this.drawerClick();
        this.top.pySourceId = item.id;
        this.$notify({
                  title: '提示',
                  message: "数据来源切换成功,当前源 " + item.name,
                  position: 'bottom-left',
                  type: 'success'
              });
      },
      //获取python数据源
      getMainPageControllerQueryCoSpiderInfoListResource(keyword,userId){
          if(this.pyResultData == null){
            Api.getMainPageControllerQueryCoSpiderInfoListResource(keyword,userId).then(response => {
                if(response.data.code == 200){
                    this.pyResultData = response.data.data
                }
                this.drawerClick();
                },
                error => {
                    this.drawerClick();
                })
            }else{
                this.drawerClick();
            }
      },
      //跳转到搜索界面
      routerPushSearch(){
          if(this.top.search == null || this.top.search.split() == ''){
              this.$notify({
                  title: '提示',
                  message: '搜索内容不能为空',
                  position: 'bottom-left',
                  type: 'warning'
              });
          }else{
            //   this.$router.push({path: '/search/' + this.top.pySourceId + '/' + this.top.search})
            // let newWindow = this.$router.resolve({path: '/search/' + this.top.pySourceId + '/' + this.top.search})
            let pyId = this.top.pySourceId == null ? this.search.pyId : this.top.pySourceId;
            this.$router.push({path: '/search/' + pyId + '/' + this.top.search}).catch(()=>{});
            // let newWindow = this.$router.resolve({path: '/search/' + pyId + '/' + this.top.search})
            // window.open(newWindow.href,'_blank')
          }
      },
      //跳转到漫画详情页
      routerPushDetail(url,pyId){
        //   this.$router.push({path: '/detail/' + pyId,
        //                     query: {
        //                             url: url
        //                          }
        //   })
          let newWindow = this.$router.resolve({path: '/detail/' + pyId,
                            query: {
                                    url: url
                                 }
          })
          window.open(newWindow.href,'_blank')
      },
      //获取历史记录
      getMainPageControllerQueryHistoryRecordPageResource(){
          if(this.top.historyData == null){
            Api.getMainPageControllerQueryHistoryRecordPageResource(this.top.pageIndex, this.top.pageSize, this.top.userId).then(response => {
                if(response.data.code == 200){
                    this.top.historyData = response.data.data
                }
            })
          }
      },
      //获取收藏信息
      getMainPageControllerCoCollectInfoPageByUserResource(){
          if(this.top.collectData == null){
            Api.getMainPageControllerCoCollectInfoPageByUserResource(this.top.pageIndex, this.top.pageSize, this.top.userId).then(response => {
                if(response.data.code == 200){
                    this.top.collectData = response.data.data
                }
            })
          }
      },
      //退出登录
      logout(){
        this.$confirm('确定退出登录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //清空token等本地用户信息
            this.$store.commit('common/update_token',null);
            this.$store.commit('common/update_username',null);
            this.$store.commit('common/update_avatar',null);
            this.$store.commit('common/update_userId',null);
            this.$store.commit('common/update_userPwd',null);
            this.$router.push("/login");
            this.$message({
            type: 'success',
            message: '退成登录成功!'
        });}).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出登录'
          });          
        });
      },
      /** 
       * 主体内容
       */
    //   //图片代理
    //   agentPicture(url,referer){
    //       let agentUrl = Api.APIROOT + '/agentController/forwardPicture?url=' + url + '&referer=' + referer
    //       return agentUrl
    //   },
      //点击跳转界面
      routerPushDetail(url){
        //   this.$router.push({path: '/detail/' + this.search.pyId,
        //                     query: {
        //                             url: url
        //                          }
        //   })
          let newWindow = this.$router.resolve({path: '/detail/' + this.search.pyId,
                            query: {
                                    url: url
                                 }
          })
          window.open(newWindow.href,'_blank')
        //   this.$router.push({path: '/search',
        //                      query: {
        //                          id: this.top.pySourceId,
        //                          keyword: this.top.search
        //                          }
        //                     })
      },
      //获取搜索结果
      getShellControllerSearchComicResource(pyId, keyword, pageIndex){
          Api.getShellControllerSearchComicResource(pyId, keyword, pageIndex).then(response => {
            if(response.data.code == 200){
                this.search.total = response.data.data.total
                this.search.data = response.data.data.data
                this.search.startLoading = true
            }
          })
      },
      load() {
        if(this.search.pageIndex < this.search.total){
            this.search.loading = true
            this.search.pageIndex = this.search.pageIndex + 1
            Api.getShellControllerSearchComicResource(this.search.pyId, this.search.keyword, this.search.pageIndex).then(response => {
                if(response.data.code == 200){
                    this.search.total = response.data.data.total
                    this.search.data.push.apply( this.search.data,response.data.data.data)
                }
            })
            // console.log("true页数加一: " + this.search.pageIndex  )
        }else{
            // console.log("false页数加一: " + this.search.pageIndex )
            this.search.loading = false
        }
      },
      //监听滚动到底部没
      listenerScroll(){
            //变量scrollTop是滚动条滚动时,距离顶部的距离
            let scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
            //变量windowHeight是可视区的高度
            let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
            //变量scrollHeight是滚动条的总高度
            let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            //滚动条到底部的条件
            if( scrollTop+windowHeight + 10 >= scrollHeight){
                //到了这个就可以进行业务逻辑加载后台数据了
                this.loading.flag = true;
                // console.log("到了底部" + this.flag);
                // window.onscroll = '' 用于解除绑定
            }else{
                this.loading.flag = false;
                // console.log("未到底部" + this.flag); 
            }   
       }
  },
  watch: {
    'loading.flag':{
        deep: true,
        handler: function(newName,oldName){
            if(newName == true && oldName == false && this.loading.flag2){
                this.loading.flag2 = false
                setTimeout(() => {
                    this.loading.flag2 = true
                }, this.loading.time);
                this.load()
                console.log("监听到了" + this.flag)
            }
        }
    }
  },
  //构造函数, 渲染界面前获取搜索内容
  mounted() {
      //判断用户登录状态,未登录则跳转到登录界面
      let token = this.$store.state.common.token;
      if(token == undefined || token == null || token == ''  || token == 'null'){
        this.$router.push("/login");
        this.$message({
            type: 'warning',
            message: '尚未登录,请登录后使用'
        });
      }else{
        // 先给页面注册滚动事件
        document.addEventListener('scroll',this.listenerScroll, true)
        //获取当前pyId的详细信息(主要获取 源 ,处理防盗链问题)
        Api.getMainPageControllerQueryCoSpiderInfoByIdResource(this.search.pyId).then(response => {
            this.search.pyInfo = response.data.data
            //获取搜索内容
            this.getShellControllerSearchComicResource(this.search.pyId,this.search.keyword,this.search.pageIndex)
        },error => {
            //获取搜索内容
            this.getShellControllerSearchComicResource(this.search.pyId,this.search.keyword,this.search.pageIndex)
        })
      }
  },
  //页面离开后销毁，防止切换路由后上一个页面监听scroll滚动事件会在新页面报错问题
  destroyed() { 
    window.removeEventListener('scroll', this.listenerScroll)
  }

}
</script>

<style scoped>
/* 布局容器 */
.el-header{
    background-color: #FFFFFF;
    color: #333;
    text-align: center;
    line-height: 60px;
    padding: 0px;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;   
    justify-content: center;
    position: sticky;
    top:0px;
    z-index: 999;
    box-shadow: 0px 0px 5px 1px rgb(211, 211, 211);
}
.el-main {
    /* background-color: #E9EEF3; */
    color: #333;
    text-align: center;
    /* line-height: 160px; */
    /* height: 100%; */
    padding: 0px;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;   
    /* justify-content: center; */
    align-items: center;
    overflow:visible;
}
/* 顶部栏 */
/* 顶部栏 */
.el-header > div:first-child {
    width: 1160px;
    /* width: 70%; */
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;   
    justify-content: center;
}
.el-header > div:first-child > div:nth-child(1){
    width: 20%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;   
    justify-content: flex-start;
    align-items: center;
}
.el-header > div:first-child > div:nth-child(2){
    width: 80%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap; 
    justify-content: flex-end;
}
.el-header > div:first-child > div:nth-child(2) > .el-menu:first-child{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap; 
}
/* 源: 抽屉 */
.my-detail-recommend{
    padding: 0% 10% 10% 10%;
}
/* 标题 */
.my-detail-recommend > div:first-child{
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    /* margin-bottom: 20px; */
}
.my-detail-recommend > div:first-child > span:first-child{
    font-size: 1.5em;
}
.my-detail-recommend > div:first-child > span:nth-child(2){
    font-size: 1em;
}
/* 内容 */
.my-detail-recommend > div:nth-child(2){
    width: 100%;
}
.my-detail-recommend-card{
    margin-top: 16px;
    width: 100%;
    height: 106px;
    display: flex;
    flex-direction: row;
    padding: 4px 0px 4px 0px;
}
.my-detail-recommend-card:hover{
    background-color: rgb(218, 218, 218);
}
.my-detail-recommend-card > div:first-child .el-image {
    width: 80px;
    height: 106px;
}
.my-detail-recommend-card > div:nth-child(2){
    width: calc(100% - 80px);
    height: 106px;
    margin-left: 12px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}  
.my-detail-recommend-card > div:nth-child(2) > span:first-child{
    font-size: 1.2em !important;
    margin-bottom: 30px;
} 
.my-detail-recommend-card > div:nth-child(2) > span:nth-child(n+1){
    font-size: 0.9em;
    margin-bottom: 15px;
} 
/* 漫画搜索 */
.my-search{
    width: 1160px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    /* justify-content: space-around; */
}
.my-search-card{
    width: 386.666px;
    height: 180px;
    margin-bottom: 32px;
    /* background-color: aqua; */
    display: flex;
    flex-direction: row;
}
.my-search-card > div:first-child > .el-image{
    width: 135px;
    height: 180px;
}
.my-search-card > div:nth-child(2) {
    width: 215.666px;
    height: 164px;
    padding: 8px 18px 8px 18px;
    display: flex;
    flex-direction: column;
    align-items: flex-start
}
.my-search-card > div:nth-child(2) span{
    font-size: 1.4em;
}
/* 漫画搜索前后提示文字 */
.start-text{
    width: 1160px;
    display: flex;
    justify-content: flex-start;
    margin: 32px 0px 32px 0px;
}
.end-text{
    width: 1160px;
    display: flex;
    justify-content: center;
    margin: 32px 0px 32px 0px;  
    font-size: 0.8em;
}

/** 其他*/
.my-search-card:hover{
    background-color: rgb(241, 241, 241);
    box-shadow: -10px 10px 10px 5px rgb(211, 211, 211);
}
.my-search-card:active{
    background-color: rgb(241, 241, 241);
    box-shadow: -10px 10px 10px 5px rgb(196, 196, 196);
}
</style>
